package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 发送短信
     */
    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean sendMsg(@RequestBody Map<String, String> map) {
        String phone = map.get("phone");
        String sendMsg = ValidateCodeUtils.generateValidateCode(4) + "";
        SMSUtils.sendMessage(phone, sendMsg);
        System.out.println("验证码:" + sendMsg);
        if (StringUtils.isNotEmpty(phone)) {
            //将验证码存放到redis中,有效期为5分钟
            redisTemplate.opsForValue().set(phone, sendMsg, 5l, TimeUnit.MINUTES);
            return true;
        }
        return false;
    }

    @Override
    public User login(HttpSession session, Map<String, String> map) {
        String phone = map.get("phone");
        //从redis中获取发送的验证码
        String sendMsg = (String) redisTemplate.opsForValue().get(phone);
        //用户输入的验证码
        String code = map.get("code");
        if (StringUtils.isNotEmpty(sendMsg) && sendMsg.equals(code)) {
            //查询数据库看用户是否是新用户
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone, phone);
            User user = userMapper.selectOne(lqw);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userMapper.insert(user);
            }
            session.setAttribute("user", user.getId());
            //删除redis中的验证码
            redisTemplate.delete(phone);
            return user;
        }
        return null;
    }

}
